package urjc.as.emergencies.client.jpanels.missions.ambulances;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;

import net.miginfocom.swing.MigLayout;

import org.restlet.data.Form;
import org.restlet.data.Response;
import org.restlet.data.Status;

import urjc.as.emergencies.client.CommToolkit;
import urjc.as.emergencies.client.DynamicTree;
import urjc.as.emergencies.client.Node;
import urjc.as.emergencies.client.TextArea;
import urjc.as.emergencies.data.Ambulance;
import urjc.as.emergencies.data.ListaAmbulancias;

@SuppressWarnings("serial")
public class PanelAmbulance extends JPanel {
	private JTextField textFieldIDAmbulancia;
	private JTextField textFieldAssignedMission;
	private JComboBox comboBoxEstado;

	private TextArea text;
	private JTree tree;
	private DynamicTree dynTree;

	private Ambulance ambulancia;

	/**
	 * Create the panel.
	 */
	public PanelAmbulance(TextArea textArea, JTree jtree, Ambulance ambulance,
			DynamicTree _dynTree) {
		this.text = textArea;
		this.tree = jtree;
		this.ambulancia = ambulance;
		this.dynTree = _dynTree;

		setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
				"Gestion Ambulancia", TitledBorder.LEADING, TitledBorder.TOP,
				null, new Color(0, 0, 255)));
		setLayout(new MigLayout("", "[90px][grow][][grow]",
				"[14px][2px][][][][][][][][][][]"));

		JLabel lblInformacinBsica = new JLabel("Información Básica");
		lblInformacinBsica.setFont(new Font("Tahoma", Font.BOLD, 11));
		add(lblInformacinBsica, "cell 0 0,alignx left,aligny top");

		JSeparator separator = new JSeparator();
		add(separator, "cell 0 1,grow");

		JLabel lblEstadoAmbulancia = new JLabel("Estado Ambulancia");
		lblEstadoAmbulancia.setForeground(Color.RED);
		lblEstadoAmbulancia.setFont(new Font("Tahoma", Font.BOLD, 11));
		add(lblEstadoAmbulancia, "cell 0 2,alignx trailing");

		comboBoxEstado = new JComboBox();
		comboBoxEstado.setForeground(Color.BLUE);
		comboBoxEstado.setFont(new Font("Tahoma", Font.BOLD, 11));
		comboBoxEstado.setModel(new DefaultComboBoxModel(new String[] {
				"Libre", "Recargando", "Atendiendo", "Descansando" }));
		add(comboBoxEstado, "cell 1 2,growx");

		JLabel lblIdAmbulancia = new JLabel("ID Ambulancia");
		lblIdAmbulancia.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblIdAmbulancia.setHorizontalAlignment(SwingConstants.RIGHT);
		add(lblIdAmbulancia, "cell 0 3,alignx left");

		textFieldIDAmbulancia = new JTextField();
		textFieldIDAmbulancia.setBackground(Color.WHITE);
		textFieldIDAmbulancia.setEditable(false);
		add(textFieldIDAmbulancia, "flowx,cell 1 3,growx");
		textFieldIDAmbulancia.setColumns(10);

		JLabel lblNewLabel = new JLabel("Tipo Ambulancia");
		lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 11));
		add(lblNewLabel, "cell 2 3,alignx trailing");

		JComboBox comboBoxAmbulanceType = new JComboBox();
		comboBoxAmbulanceType.setModel(new DefaultComboBoxModel(new String[] {
				"UVI Movil", "UAD", "Ambulancia Normal" }));
		add(comboBoxAmbulanceType, "cell 3 3,growx");
		comboBoxAmbulanceType.setEditable(false);

		JLabel lblInformacionMisin = new JLabel("Informacion Misión");
		lblInformacionMisin.setFont(new Font("Tahoma", Font.BOLD, 11));
		add(lblInformacionMisin, "cell 0 5");

		JSeparator separator_1 = new JSeparator();
		add(separator_1, "cell 0 6,grow");

		JLabel lblMisinAsignada = new JLabel("Misión Asignada");
		lblMisinAsignada.setFont(new Font("Tahoma", Font.BOLD, 11));
		add(lblMisinAsignada, "cell 0 7,alignx left");

		textFieldAssignedMission = new JTextField();
		textFieldAssignedMission.setEditable(false);
		textFieldAssignedMission.setBackground(Color.WHITE);
		add(textFieldAssignedMission, "cell 1 7,growx");
		textFieldAssignedMission.setColumns(10);

		JButton buttonCommit = new JButton("Actualizar Ambulancia");
		buttonCommit.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();

				if (node != null) {
					// Obtenemos la URI asociada al nodo seleccionado
					Node nodeInfo = (Node) node.getUserObject();
					String targetURI = nodeInfo.getUri();

					// Creo el formulario con las modificaciones
					Form form = new Form();
					form.add("estado", comboBoxEstado.getSelectedItem()
							.toString());
					// form.add("id", textFieldIDAmbulancia.getText());
					// form.add("misionId", textFieldAssignedMission.getText());

					// Hacemos la petición para crear un nuevo mailbox de
					// usuario, sobre la URL adecuada
					Status state = CommToolkit.sendPatch(targetURI, form);

					// Se muestra el estado
					text.append(state.getDescription());

					// Deseleccionamos el nodo del árbol
					tree.clearSelection();
				}

			}
		});
		add(buttonCommit, "cell 0 9 4 1,alignx center,aligny center");

		// Actualizar informacion en la GUI con los datos
		textFieldIDAmbulancia.setText(ambulance.getId() + "");
		textFieldAssignedMission.setText(ambulance.getMisionId() + "");
		comboBoxEstado.setSelectedItem(ambulance.getStringStauts());
		comboBoxAmbulanceType.setSelectedItem(ambulance.getType());

		JButton btnNewButton = new JButton("Borrar Ambulancia");
		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				// Desvincular ambulancia en Storage
				Status status = deleteAmbulance();
				if (status.equals(Status.SUCCESS_OK)) {
					text.append(status.getDescription());

					// Borrar ambulancia de la lista de ambulancias
					// 1) Peticion GET a la lista de ambulancias
					ListaAmbulancias ambulances = (ListaAmbulancias) CommToolkit
							.getRepresentation(CommToolkit.AMBULANCES);

					// 2) Elimino la ambulancia concreta de la lista
					ambulances.eliminarAmbulancia(ambulancia.getUri());

					// 3) Peticiones PUT para actualizar el recurso completo
					Response response = CommToolkit.doPut(ambulances);

					text.append(response.getStatus().getDescription());

					// Borramos el nodo
					dynTree.deleteNode(dynTree.getLastSelectedNode());
				} else {
					text.append(status.getDescription());
				}
			}
		});
		add(btnNewButton, "cell 1 11 2 1,alignx center");
	}

	/**
	 * Envia una peticion de borrado del recurso ambulancia
	 * 
	 * @return status de la peticion
	 */
	protected Status deleteAmbulance() {
		Response response = CommToolkit.sendDelete(ambulancia);
		return response.getStatus();
	}

}
